#include "netserver_udp.h"

Netserver_udp::Netserver_udp(QString setserverip,int setserverport,int setlistenport)
{
    m_ServerIP = setserverip;//要发给服务器的IP
    m_ServerPort = setserverport;//要发向服务器的端口
    m_ListenPort = setlistenport;//要接收消息的端口

    m_UdpDescribe = new QUdpSocket;

    if(false == m_UdpDescribe->bind(QHostAddress::Any, m_ListenPort)){
        qDebug()<<"Bind error!";
        exit(1);
    }
}

Netserver_udp::~Netserver_udp()
{
    delete m_UdpDescribe;
}

QByteArray Netserver_udp::m_ReciveMessageProcess()
{
    QByteArray datagram;
    while (m_UdpDescribe->hasPendingDatagrams()) {
             datagram.resize(m_UdpDescribe->pendingDatagramSize());
             QHostAddress sender;
             quint16 senderPort;
             m_UdpDescribe->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);
         }
    qDebug()<<datagram;
    return datagram;
}

void Netserver_udp::m_SendMessageProcess(QByteArray send_data)
{
    QHostAddress address(m_ServerIP);//server IP
    m_UdpDescribe->writeDatagram(send_data, address, m_ServerPort);//server port

    qDebug()<<"Senddata:"<<send_data;
}

QString Netserver_udp::m_GetIp()
{
    QList<QHostAddress> NetList = QNetworkInterface::allAddresses(); //取得全部信息
    for(int Neti = 0; Neti < NetList.count(); Neti++){
        if(NetList.at(Neti).toString().count() < 16 && false == NetList.at(Neti).toString().contains("127.0.0.1") && false == NetList.at(Neti).toString().contains(":")){
            qDebug()<<"IP:"<<NetList.at(Neti).toString();
            return NetList.at(Neti).toString();
        }
    }
    qDebug()<<"IP get error!";
    exit(2);
}
